package com.ueboot.weishop.service.role.impl;

import com.ueboot.weishop.entity.role.Resources;
import com.ueboot.weishop.entity.role.Role;
import com.ueboot.weishop.repository.role.PermissionRepository;
import com.ueboot.weishop.repository.role.ResourcesRepository;
import com.ueboot.weishop.repository.role.UserRoleRepository;
import com.ueboot.weishop.service.role.ResourcesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Neel on 2017/9/20.
 */

@Slf4j
@Service
public class ResourcesServiceImpl implements ResourcesService {

    @Autowired
    private ResourcesRepository repository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public Page<Resources> findBy(Pageable pageable) {
        return repository.findAll(pageable);
    }


    @Override
    public Resources save(Resources s) {
        return repository.save(s);
    }

    @Override
    public Resources get(Long id) {
        return repository.findOne(id);
    }

    @Override
    public void delete(Long[] ids) {
        for (Long id : ids) {
            repository.delete(id);
        }
    }

    @Override
    public void delete(Long id) {
        repository.delete(id);
    }

    /**
     * 根据用户名获取菜单资源
     * @param username
     * @return
     */
    @Override
    public Resources[] getUserResources(String username) {
        Set<Resources> list = new HashSet<>();

        List<Role> roles = this.userRoleRepository.findByUsername(username);
        for (Role role : roles) {
            List<Resources> resources = this.permissionRepository.findByRoleAndResourceType(role.getRole(), Resources.RESOURCE_TYPE_MENU);
            list.addAll(resources);
        }
        Resources[] result = new Resources[list.size()];
        list.toArray(result);
        Arrays.sort(result, Comparator.comparing(Resources::getRank, Comparator.reverseOrder()));
        return result;
    }
}
